const axios = require('axios')
const userDao = require('../dao/user')
const cashbookDao = require('../dao/cashbook')
const { APP_ID, APP_SECRET } = require('../../config')

module.exports = {

    login: async function (req, res) {
        const { code } = req.query

        if (!code) {
            return res.json({ code: '9999', message: 'code不能为空', data: {} })
        }

        try {
            // 根据code拿到openid 
            const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${APP_SECRET}&js_code=${code}&grant_type=authorization_code`
            const wxResult = await axios.get(url)
            const { openid } = wxResult.data

            // 根据 openid 去用户表里面查询数据
            const userResult = await userDao.getUser({ username: openid, password: openid })
            const user = userResult.data

            // 用户存在
            if (user.id) {
                const cashbookResult = await cashbookDao.getCashbookList({ coopUserId: user.id })
                return res.json({
                    code: '0000',
                    message: '操作成功',
                    data: {
                        userId: user.id,
                        cashbooks: cashbookResult.data || [],
                        nickname: user.nickname,
                        avatarUrl:user.avatar_url,

                    },
                })
            }

            // 如果没有查到数据， 新增一条用户信息
            const saveResult = await userDao.saveUser({ username: openid, password: openid })
            const userId = saveResult.data.insertId

            // 新增默认记账本
            const cashbookResult = await cashbookDao.saveCashbook({ belongUserId: userId })

            res.json({
                code: '0000',
                message: '操作成功',
                data: {
                    userId,
                    cashbooks: [
                        { 
                            id: cashbookResult.data.insertId,
                            name: '默认账本', 
                        },
                    ],
                },
            })
        } catch (e) {
            console.log('[-] routes > weapp > login()', e.message)
            res.json({ code: '9999', message: '登录失败', data: {} })
        }
    },

}